package com.logDataBase;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.hfut.dmic.webcollector.crawler.Crawler;
import cn.edu.hfut.dmic.webcollector.fetcher.Fetcher;

import com.model.LogDateBaseSingletion;
import com.tool.LogDataBaseSqlTool;
import com.tool.LogDataBaseTool;

/**
 * *********************************************
 * @author Administrator
 * @FileName LogMonitor.java
 * @Description日志监控(爬虫程序自动报告)
 **********************************************
 */
public class LogMonitor implements Runnable {
	public static final Logger LOG = LoggerFactory.getLogger(LogMonitor.class);
	
	private boolean run = true;
	private String xmlFileName;
	private int seconds;
	private Crawler crawler;
	
	public LogMonitor(){}
	
	public LogMonitor(String xmlFileName,int delay,Crawler crawler) {
		this.xmlFileName = xmlFileName;
		this.seconds = delay;
		this.crawler = crawler;
	}
	
	@Override
	public void run() {
		while (run) {
			Fetcher fetcher = crawler.getFetcher();
			if(fetcher != null && fetcher.getFinishedSeeds() != null){
				int finished_seeds = fetcher.getFinishedSeeds().get();
				LOG.info("执行中,已完成" + finished_seeds + "个种子");
				LogDataBaseTool.update(LogDateBaseSingletion.getSingle().getDataBaseName(), 
						LogDataBaseSqlTool.getLogDataBase_executeCrawler(), 
						new Object[]{finished_seeds,xmlFileName});
			}
			
			try {
				Thread.sleep(seconds * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void shutdown() {
		this.run = false;
		Fetcher fetcher = crawler.getFetcher();
		if(fetcher != null && fetcher.getFinishedSeeds() != null){
			int finished_seeds = fetcher.getFinishedSeeds().get();
			LOG.info("执行中,已完成" + finished_seeds + "个种子");
			LogDataBaseTool.update(LogDateBaseSingletion.getSingle().getDataBaseName(), 
					LogDataBaseSqlTool.getLogDataBase_executeCrawler(), 
					new Object[]{finished_seeds,xmlFileName});
		}
	}

}
